package me.seawenc.datastash.helper;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

public class FileHelper {
    public static Properties readExtResFile(String path) throws Exception {
        // 过滤掉注释行
        List<String> strings = readExtFile(path).stream().map(line-> line.trim())
                .filter(line->!line.startsWith("#"))
                .filter(line->line.contains("="))
                .collect(Collectors.toList());
        Properties props=new Properties();
        for (String line:strings){
            int index = line.indexOf("=");
            props.setProperty(line.substring(0,index).trim(),line.substring(index+1).trim());
        }
        return props;
    }
    /**
     * 读取项目外部的文件,一行一条记录
     * @param path
     * @return
     * @throws Exception
     */
    public static List<String> readExtFile(String path) throws Exception {
        InputStream inputStream=new FileInputStream(path);
        List<String> strings = readStreamToList(String.class, inputStream);
        inputStream.close();
        return strings;
    }

    public static <T> List<T> readStreamToList(Class<T> clazz, InputStream in) throws IOException {
        InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
        BufferedReader reader = new BufferedReader(inReader);
        List<String> lines=new ArrayList<>();
        String line;
        while(reader.ready()&&(line = reader.readLine()) != null){
            lines.add(line);
        }
        //如果是格式化过后的文件，则合并成一条数据
//        if(lines.get(0).equals("{")){
        if("{".equals(lines.get(0))){
            line=String.join("",lines.toArray(new String[]{}));
            lines.clear();
            lines.add(line);
        }
        //将对旬格式转换成指定对象
        List<T> ret=new ArrayList<>();
        for(String s:lines){
            if(clazz.getSimpleName().equals(String.class.getSimpleName())){
                ret.add((T)s);
                continue;
            }
            ret.add(JSONObject.parseObject(s, clazz));
        }
        reader.close();
        inReader.close();
        in.close();
        return ret;
    }

}
